package com.tanhua.sso.interceptor;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tanhua.common.mapper.UserMapper;
import com.tanhua.common.pojo.User;
import com.tanhua.dubbo.server.api.ManageFreezeApi;
import com.tanhua.dubbo.server.enums.FreezingRangeEnum;
import com.tanhua.sso.service.UserInfoService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;

/**
 * 该拦截器提供的功能是对token进行拦截校验,判断又是否被冻结
 */
@Component
@Slf4j
public class TokenCheckInterceptor implements HandlerInterceptor {
    @Autowired
    private UserInfoService userInfoService;
    @Reference(version = "1.0.0")
    private ManageFreezeApi manageFreezeApi;
    @Autowired
    private UserMapper userMapper;

    /**
     * 实现功能：对冻结用户进行拦截
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {


        //看有没有token
        String token = request.getHeader("Authorization");
        //判断token是否为空
        if (StringUtils.isNotEmpty(token)) {
            //获取用户信息
            User user = userInfoService.checkToken(token);
            Boolean result1 = manageFreezeApi.isAccountState(Convert.toInt(user.getId()), FreezingRangeEnum.MAKE);
            Boolean result2 = manageFreezeApi.isAccountState(Convert.toInt(user.getId()), FreezingRangeEnum.DYNAMIC);
            Boolean result3 = manageFreezeApi.isAccountState(Convert.toInt(user.getId()), FreezingRangeEnum.REGISTER);
            Boolean accountState = result1 || result2 || result3;
            //判断用户是否冻结
            if (accountState) {
                //冻结
                return false;
            }
        }
        //未冻结
        return true;

    }


}
